import Taro, { useState } from "@tarojs/taro";
import { Button, View } from "@tarojs/components";
import "./index.scss";
import { CustomRequest } from "@/utils/request";

export interface IAvatarPermissionContainer {
  children: JSX.Element;
  reLaunchPath?: string;
}

export const PhonePermissionClickContainer = (
  props: IAvatarPermissionContainer
) => {
  const { children } = props;

  const userInfo = Taro.getStorageSync("userInfo");

  const phone = userInfo ? userInfo.tel : "";

  const [userPhone, setUserPhone] = useState(phone);

  const getPhoneNumberCallback = (e: any) => {
    console.log(e);
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      CustomRequest.post("/api/auth/app/v1/phone", {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv
      })
        .then((res: any) => {
          if (res.data) {
            Taro.setStorageSync("userInfo", res.data);
            setUserPhone(res.data.tel);
          }
        })
        .catch(_err => {
          Taro.showToast({
            title: "手机号授权失败,请稍后重试",
            icon: "none",
            duration: 2000
          });
        });
    }
  };
  return (
    <View className="phone-permission-container">
      {children}
      {!userPhone ? (
        <Button
          openType="getPhoneNumber"
          className="btn"
          onGetPhoneNumber={getPhoneNumberCallback}
        ></Button>
      ) : (
        ""
      )}
    </View>
  );
};
